# -*- coding: utf-8 -*-
"""
@Time : 2024/5/27 10:31
@Author : ChenXiaoliang
@Email : middlegod@sina.com
@File : get_userid_by_name.py
"""
from bs4 import BeautifulSoup
import requests
from urllib.parse import quote


def get_userid_by_name(name):
    """
    通过用户名获取用户id
    :param name: 用户名
    :return: 用户id
    """
    user_encode = quote(name)
    # print(user_input, user_encode)

    url = f'https://s.weibo.com/user?q={user_encode}'
    referer = f'https://s.weibo.com/weibo?q={user_encode}'
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36",
        "Referer": referer,
        "Cookie": "SUB=_2AkMRBb7odavRIYgFDYmUOPezr3SUzDg2yl"}
    res = requests.get(url, headers=headers)
    # print(res.content)
    soup = BeautifulSoup(res.text, 'html.parser')
    user_ls = soup.find(class_='card-wrap').find_all(class_='card')

    user_result = []
    target_user_id = ''
    for user in user_ls:
        user_name = user.find(class_='name').text
        user_id = user.find(class_='name').get('href').split('/')[-1]
        profile = user.find(class_='info').find_all('p')[0].text if len(
            user.find(class_='info').find_all('p')) > 1 else None
        follower = user.find(class_='s-nobr').text

        user_result.append({"name": user_name, "user_id": user_id, "profile": profile, "follower": follower})
        # print(name)
        # print(user_id)
        # print(profile)
        # print(follower)
        # print("=" * 50)

        if user_name == name:
            target_user_id = user_id

    print(f"{name}对应id：{target_user_id}\n")
    return target_user_id


if __name__ == '__main__':
    get_userid_by_name("国家图书馆")
